import { setCookie, getCookie, delCookie } from '@/utils/storage'
export default function userReducer(
  // 设置默认值
  state = {
    token: getCookie('token') || '',
    userinfo: JSON.parse(getCookie('userinfo') || '{}'),
  },
  action
) {
  const { type, payload } = action
  if (type === 'LOGIN') {
    // 登录
    // 持久化存储token
    setCookie('token', payload.token)
    return payload
  } else if (type === 'LOGOUT') {
    // 删除持久化数据
    delCookie('token')
    delCookie('userinfo')
    return payload
  } else if (type === 'GET_PROFILE') {
    // 获取用户信息
    // 持久化存储token,js-cookie存对象需要先转成字符串
    setCookie('userinfo', JSON.stringify(payload.userinfo))
    return payload
  }
  return state
}
